package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WemediaFeign;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.admin.pojos.AdSensitive;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private AdSensitiveMapper adSensitiveMapper;
    @Autowired
    private GreenImageScan greenImageScan;
    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdChannelMapper adChannelMapper;

    /**
     * 自媒体文章审核
     * @param id
     */
    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        if (id==null){
            throw new RuntimeException("自媒体文章id不存在");
        }

        //1、根据id查询自媒体文章信息
        WmNews wmNews = wemediaFeign.findNewsById(id);
        if (wmNews==null){
            throw new RuntimeException("自媒体文章不存在");
        }

        //2、文章状态为4（人工审查通过）直接保存数据和创建索引
        if (wmNews.getStatus()==4 && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            saveAppArticle(wmNews);
            return;
        }

        //3、文章状态为8 发布时间小于当前时间，直接保存
        if (wmNews.getStatus()==8 && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            saveAppArticle(wmNews);
            return;
        }

        //4、文章状态为1 待审核
        if (wmNews.getStatus()==1){
            //抽取文章内容中的纯文本和图片
            Map<String,Object> contentAndImages = handleTextAndImages(wmNews);
            //4.1 调用阿里云反文本垃圾
            boolean isTextScan = handleTextScan((String)contentAndImages.get("content"),wmNews);
            if (!isTextScan) return;
            //4.2 阿里云图片审核
            boolean isImageScan = handleImageScan((List<String>)contentAndImages.get("images"),wmNews);
            if (!isImageScan) return;
            //4.3 文章是否包含自定义的敏感词
            boolean isSensitive = handleSensitive((String)contentAndImages.get("content"),wmNews);
            if (!isSensitive) return;
            //4.4 发布时间大于当前时间，修改文章状态为8
            if (wmNews.getPublishTime()!=null&&wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
                updateWmNews(wmNews,(short)8,"审核通过，待发布");
                return;
            }
            //4.5 审核通过，修改自媒体文章状态为9 保存app端的相关数据
            saveAppArticle(wmNews);
        }
    }

    /**
     * 修改文章
     * @param wmNews
     * @param status 文章状态
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.getCode().equals(0)){
            throw new RuntimeException("修改自媒体文章失败");
        }
    }

    /**
     * 自管理敏感词审核
     * @param content 文章内容
     * @param wmNews
     * @return 是否审核通过
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag=true;
        //获取所有自定义的敏感词
        List<AdSensitive> sensitivesList = adSensitiveMapper.selectList(Wrappers.<AdSensitive>lambdaQuery().select(AdSensitive::getSensitives));
        List<String> allSensitive = sensitivesList.stream().map(AdSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(allSensitive);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size()>0){
            updateWmNews(wmNews, (short) 2,"文章中包含敏感词："+map);
            flag=false;
        }
        return flag;
    }

    /**
     * 图片审核
     * @param images 图片
     * @param wmNews
     * @return 是否审核通过
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        if (images==null||images.size()==0){//没有图片，无需审核
            return true;
        }
        boolean flag=true;
        List<byte[]> imageList = new ArrayList<>();
        try {
            for (String image : images) {
                if (StringUtils.isEmpty(image)) continue;
                String imageName = image.replace(fileServerUrl, "");
                int index = imageName.indexOf("/");//返回第一次出现的下标
                String groupName = imageName.substring(0,index);
                String imagePath = imageName.substring(index+1);
                byte[] download = fastDFSClient.download(groupName, imagePath);
                imageList.add(download);
            }
            Map map = greenImageScan.imageScan(imageList);
            //审核不通过
            if (map.get("suggestion").equals("block")){
                updateWmNews(wmNews, (short) 2,"文章图片涉嫌违规");
                flag = false;
            }
            //人工审核
            if (map.get("suggestion").equals("review")){
                updateWmNews(wmNews, (short) 3,"文章图片有不确定元素，需要人工审核");
                flag = false;
            }
        }catch (Exception e){
            e.printStackTrace();
            flag=false;
        }
        return flag;
    }

    /**
     * 文本审核
     * @param content 文本内容
     * @param wmNews
     * @return 是否审核通过
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greeTextScan(content);
            //审核不通过
            if (map.get("suggestion").equals("block")){
                updateWmNews(wmNews, (short) 2,"文本内容中有敏感词汇");
                flag = false;
            }
            //人工审核
            if (map.get("suggestion").equals("review")){
                updateWmNews(wmNews, (short) 3,"文本内容中有不确定词汇，需要人工审核");
                flag = false;
            }
        }catch (Exception e){
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 抽取自媒体文章的文本和图片   其中图片包含了 文章正文内容和封面图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //自媒体文章正文内容
        String content = wmNews.getContent();
        //纯文本内容
        StringBuilder sb = new StringBuilder();
        //图片内容
        List<String> images = new ArrayList<>();
        List<Map> contentList = JSONArray.parseArray(wmNews.getContent(), Map.class);
        for (Map map : contentList) {
            //文本
            if (map.get("type").equals("text")){
                sb.append(map.get("value"));
            }
            //图片
            if (map.get("type").equals("image")){
                images.add((String) map.get("value"));
            }
        }
        //自媒体文章的封面图片
        if (wmNews.getId() != null) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        //返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", sb.toString());
        resultMap.put("images", images);
        return resultMap;
    }

    /**
     * 保存app端相关文章
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        //保存app相关文章
        ResponseResult responseResult = saveArticle(wmNews);
        if (!responseResult.getCode().equals(0)){
            throw new RuntimeException("文章审核保存app文章失败");
        }
        Object data = responseResult.getData();
        //修改自媒体文章状态，状态为9  审核通过
        wmNews.setArticleId((Long) data);
        updateWmNews(wmNews,(short) 9,"文章审核通过");

        //TODO 创建es索引
    }

    /**
     * 保存app文章
     * @param wmNews
     * @return
     */
    private ResponseResult saveArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        if(wmNews.getArticleId() != null){
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setPublishTime(wmNews.getPublishTime());
        articleDto.setImages(wmNews.getImages());
        articleDto.setTitle(wmNews.getTitle());
        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());
        //设置频道
        AdChannel channel = adChannelMapper.selectById(wmNews.getChannelId());
        if(channel != null){
            articleDto.setChannelId(channel.getId());
            articleDto.setChannelName(channel.getName());
        }
        //设置作者信息
        WmUser wmUser = wemediaFeign.findWmUserById(wmNews.getUserId().longValue());
        articleDto.setAuthorName(wmUser.getName());
        articleDto.setContent(wmNews.getContent());

        return articleFeign.saveArticle(articleDto);
    }
}
